package com.shanjupay.merchant.controller;

import com.shanjupay.common.exception.BusinessException;
import com.shanjupay.common.exception.CommonErrorCode;
import com.shanjupay.common.util.PhoneUtil;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.convert.MerchantDetailConvert;
import com.shanjupay.merchant.convert.MerchantRegisterConvert;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.utils.SecurityUtil;
import com.shanjupay.merchant.vo.MerchantDetailVO;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.BatchUpdateException;
import java.util.UUID;


/**
 * @author Administrator
 * @version 1.0
 **/
@RestController
@Slf4j
@Api(value="商户平台应用接口",tags = "商户平台应用接口",description = "商户平台应用接口")
public class MerchantController {

    @org.apache.dubbo.config.annotation.Reference
    MerchantService merchantService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private FileService fileService;

    /**
     * 按id查询商户
     *
     * @param id id
     * @return {@link MerchantDTO}
     */
    @ApiOperation(value="根据id查询商户信息")
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id){
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    /**
     * 获取短信代码
     *
     * @param phone 电话
     * @return {@link String}
     */
    @GetMapping("/sms")
    public String getSmsCode(@RequestParam String phone){
        log.info("向手机号:{}发送验证码", phone);
        return smsService.getSmsCode(phone);
    }

    /**
     * 注册商户
     *
     * @param merchantRegister 商户登记簿
     * @return {@link MerchantRegisterVO}
     */
    @PostMapping("/merchants/register")
    public MerchantRegisterVO registerMerchant(@RequestBody MerchantRegisterVO merchantRegister){
        // 校验
        if (merchantRegister == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        //手机号非空校验
        if (StringUtils.isBlank(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //校验手机号的合法性
        if (!PhoneUtil.isMatches(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        //联系人非空校验
        if (StringUtils.isBlank(merchantRegister.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
        //密码非空校验
        if (StringUtils.isBlank(merchantRegister.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }
        //验证码非空校验
        if (StringUtils.isBlank(merchantRegister.getVerifiyCode()) ||
                StringUtils.isBlank(merchantRegister.getVerifiykey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }

        // 校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(),merchantRegister.getVerifiyCode());
        // 注册商家
        /*MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setUsername(merchantRegister.getUsername());
        merchantDTO.setPassword(merchantRegister.getPassword());
        merchantDTO.setMobile(merchantRegister.getMobile());*/
        // 将vo转dto
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegister);

        merchantService.createMerchant(merchantDTO);  // 调用Dubbo进行存储商家信息
        return merchantRegister;
    }

    /**
     * 上传
     *
     * @param file 文件
     * @return {@link String}
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
        // 拼接后的文件名称
        String fileName = UUID.randomUUID().toString()+suffix;
        try {
            return fileService.upload(file.getBytes(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100106);
        }
    }

    /**
     * 申请商户资质
     *
     * @param merchantDetailVO 商户详细信息vo
     */
    @PostMapping("/my/merchants/save")
    public void applyMerchant(@RequestBody MerchantDetailVO merchantDetailVO){
        // 解析出token,取出当前登录用户的id
        Long merchantId = SecurityUtil.getMerchantId();
        System.out.println("merchantId = " + merchantId);

        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantDetailVO);

        try {
            merchantService.applyMerchant(merchantId,merchantDTO);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
    }
}
